package com.hbpu.encap.socket.homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Homework03ServerCopy {
    public static void main(String[] args) throws InterruptedException {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("Waiting for connection...");
            String s = "Briet - Twin.flac";
            try (Socket socket = serverSocket.accept()) {
                System.out.println("Accepted connection from " + socket.getLocalSocketAddress());

                // 获取输入流读取客户端发送的文件名
                try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                    s = in.readLine();
                    // 使用同一个输出流对象完成文件传输和反馈消息发送
                    try (DataOutputStream outStream = new DataOutputStream(socket.getOutputStream())) {
                        // 发送文件内容
                        try (BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream("C:\\Users\\马可\\Music\\" + s))) {
                            System.out.println("文件已找到");
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = fileIn.read(buffer)) != -1) {
                                outStream.write(buffer, 0, len);
                            }
                            outStream.flush();
                            System.out.println("文件成功发送！");

                            Thread.sleep(5000);

                            try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outStream))) {
                                bufferedWriter.write("已向你发送：" + s + " 音乐文件");
                                bufferedWriter.newLine();
                                bufferedWriter.flush();
                            } catch (IOException e) {
                                System.out.println("回复发送失败！" + e.getMessage());
                            }

                        } catch (IOException e) {
                            System.out.println("文件发送失败！" + e.getMessage());
                        }
                    } catch (IOException e) {
                        System.out.println("Error: " + e);
                    }
                } catch (IOException e) {
                    System.out.println("Error: " + e);
                }
                } catch (IOException e) {
                    System.out.println("Error: " + e);
                }


        } catch (IOException e) {
            System.out.println("等待连接时出现错误！" + e.getMessage());
        }

    }
}
